package com.ross.service.impl;

import com.ross.dao.SysRolesMapper;
import com.ross.pojo.SysPermissions;
import com.ross.pojo.SysRoles;
import com.ross.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author RossZhang
 */
@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private SysRolesMapper roleMapper;

    /**
     * 查询表中是否存在此数据
     * @param roleId
     * @param permissionId
     * @return
     */
    private boolean exists(Long roleId, Long permissionId) {
        return roleMapper.exists(roleId, permissionId);
    }

    @Override
    public void correlationPermissions(Long roleId, Long... permissionIds) {
        if (permissionIds == null || permissionIds.length == 0){
            return;
        }
        for (Long permissionId : permissionIds){
            if (!exists(roleId,permissionId)){
                this.roleMapper.correlationPermissions(roleId,permissionId);
            }
        }
    }

    @Override
    public void uncorrelationPermissions(Long roleId, Long... permissionIds) {
        if (roleId == null || permissionIds.length == 0){
            return;
        }
        for (Long permissionId : permissionIds){
            if (exists(roleId,permissionId)){
                this.roleMapper.uncorrelationPermissions(roleId,permissionId);
            }
        }
    }

    @Override
    public List<SysPermissions> findRolePermissionByRoleId(Long id) {
        return this.roleMapper.findRolePermissionByRoleId(id);
    }

    @Override
    public List<SysPermissions> findPermissionByRoleId(Long id) {
        return this.roleMapper.findPermissionByRoleId(id);
    }

    @Override
    public void deleteAllRolePermissions(Long id) {
        this.roleMapper.deleteAllRolePermissions(id);
    }

    @Override
    public void updateUserRole_Id(SysRoles role) {
        this.roleMapper.updateUserRole_Id(role);
    }

    @Override
    public SysRoles findById(Long id) {
        return this.roleMapper.findById(id);
    }

    @Override
    public void create(SysRoles sysRoles) {
        this.roleMapper.create(sysRoles);
    }

    @Override
    public void delete(Long id) {
        //先将和角色相关的表删除
        this.roleMapper.deleteUserRole(id);
        //再删除角色表数据
        this.roleMapper.deleteRole(id);
    }

    @Override
    public void update(SysRoles sysRoles) {
        this.roleMapper.update(sysRoles);
    }

    @Override
    public List<SysRoles> findAll() {
        return this.roleMapper.findAll();
    }
}
